import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:film/controller/auth_controller.dart';
import 'package:film/model/film_model.dart';
import 'package:film/service/api_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:gif/gif.dart';
import 'package:super_player/super_player.dart';

class FilmScreen extends StatefulWidget {
  const FilmScreen({Key? key}) : super(key: key);

  @override
  _FilmScreenState createState() => _FilmScreenState();
}

class _FilmScreenState extends State<FilmScreen> {
  AuthController authController = Get.find();
  final TXVodPlayerController _controller = TXVodPlayerController();
  final DioService dioService = DioService();
  bool _isFullScreen = false;
  bool _showControls = false;
  // _isInitialized 已被移除，播放器状态由事件驱动
  var _isLoading = true.obs;
  Timer? _hideControlsTimer;
  var url;
  var vodId;

  // --- 新增：用于管理播放器状态的响应式变量 ---
  final _isPlaying = false.obs;
  final _isPlayEnd = false.obs;
  final _currentPosition = Duration.zero.obs;
  final _totalDuration = Duration.zero.obs;
  // ---

  // 影片列表
  var recommendFilmList = <Film>[].obs;
  var film = Film().obs;
  var videoItemList = <VideoItem>[].obs;
  final selectedEpisodeIndex = 0.obs;

  // 使用剧集code来追踪选中项，这样排序后也能正确定位
  final selectedEpisodeCode = ''.obs;
  // 控制剧集列表是否倒序
  final isEpisodeListReversed = false.obs;

  @override
  void initState() {
    super.initState();
    url = Get.arguments['url'];
    vodId = Get.arguments['vodId'];
    _initializePlayer();
    _initializeVideo();
  }

  /// 初始化播放器并监听事件
  void _initializePlayer() {
    // 注册事件监听
    _controller.onPlayerEventBroadcast.listen((event) {
      print('事件: $event');
      final int code = event["event"];
      switch (code) {
        case TXVodPlayEvent.PLAY_EVT_VOD_PLAY_PREPARED: // 播放器准备就绪
        case TXVodPlayEvent.PLAY_EVT_PLAY_BEGIN: // 开始播放
          _isLoading.value = false;
          _isPlaying.value = true;
          _isPlayEnd.value = false;
          break;
        case TXVodPlayEvent.PLAY_EVT_PLAY_LOADING: // 缓冲开始
          // _isLoading.value = true;
          break;
        case TXVodPlayEvent.PLAY_EVT_PLAY_PROGRESS: // 播放进度更新
          final progress = event[TXVodPlayEvent.EVT_PLAY_PROGRESS_MS] ?? 0;
          final duration = event[TXVodPlayEvent.EVT_PLAY_DURATION_MS] ?? 0;
          _currentPosition.value = Duration(milliseconds: progress);
          _totalDuration.value = Duration(milliseconds: duration);
          if (_isLoading.value) {
            // _isLoading.value = false; // 如果在加载，收到进度意味着加载结束
          }
          break;
        // case TXVodPlayEvent.PLAY_EVT_PLAY_PAUSE: // 暂停
        //   _isPlaying.value = false;
        //   break;
        case TXVodPlayEvent.PLAY_EVT_PLAY_END: // 播放结束
          _isPlaying.value = false;
          _isPlayEnd.value = true;
          break;
        // 可在此处处理其他事件，如网络断开错误
      }
    });

    // 开始播放
    try {
      _controller.startVodPlay(url);
    } catch (e) {
      print('初始化错误: ${e}');
    }
  }

  /// 获取视频
  Future<void> _initializeVideo() async {
    try {
      final ApiResponse<VideoDetails> response = await dioService.getVideoByID(vodId: vodId);
      if (response.success && response.data != null) {
        film.value = Film.fromJson(response.data!.video);
        videoItemList.value = parseVideoItems(film.value.vodPlayUrl ?? "");
        getRecommendFilmList(film.value.vodYear!);
        dioService.addVideoRecord(videoId: vodId, look: '1');
      }
    } catch (e) {
      print('获取视频失败: $e');
    }
  }

  /// 获取推荐视频
  Future<void> getRecommendFilmList(String vodYear) async {
    try {
      SearchCriteria criteria = SearchCriteria(page: "1", limit: "12", resultType: "1", vodYear: vodYear);
      ApiResponse<List<Film>> response = await dioService.searchVideo(criteria);
      if (response.success) {
        recommendFilmList.assignAll(response.data ?? []);
      }
    } catch (e) {
      print('获取推荐视频失败: $e');
    }
  }

  /// 添加视频记录(观看记录|追番记录)
  Future<void> addVideoRecord(
    String videoId,
    String follow,
  ) async {
    final ApiResponse<void> response = await dioService.addVideoRecord(
      videoId: videoId,
      follow: follow,
    );
    if (response.success) {
      Get.snackbar(
        '成功',
        '追番成功！',
        duration: Duration(seconds: 1),
      );
    }
  }

  List<VideoItem> parseVideoItems(String vodPlayUrl) {
    final List<VideoItem> result = [];
    final episodes = vodPlayUrl.split('#');
    for (var episode in episodes) {
      final parts = episode.split('\$');
      if (parts.length == 2) {
        result.add(VideoItem(
          name: parts[0].trim(),
          code: parts[1].trim(),
        ));
      }
    }
    return result;
  }

  /// 选择剧集
  Future<void> selectEpisode(String urlKey) async {
    try {
      _isLoading.value = true;
      _currentPosition.value = Duration.zero; // 重置进度
      _totalDuration.value = Duration.zero; // 重置总时长
      final ApiResponse<String> res = await dioService.getVideoUrl(url: urlKey);
      if (res.success && res.data != null) {
        url = res.data!;
        await _controller.stop(isNeedClear: true); // 停止当前播放并清空画面
        await _controller.startVodPlay(url); // 播放新地址
      } else {
        _isLoading.value = false;
      }
    } catch (e) {
      print('切换剧集失败: $e');
      _isLoading.value = false;
    }
  }

  @override
  void dispose() {
    if (_isFullScreen) {
      _exitFullScreen();
    }
    _hideControlsTimer?.cancel(); // 安全地取消计时器
    _controller.dispose();
    super.dispose();
  }

  void _toggleFullScreen() {
    setState(() {
      _isFullScreen = !_isFullScreen;
      if (_isFullScreen) {
        SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.landscapeLeft,
          DeviceOrientation.landscapeRight,
        ]);
      } else {
        _exitFullScreen();
      }
    });
    // 切换全屏后，重置隐藏控件的计时器
    _startHideControlsTimer();
  }

  void _exitFullScreen() {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: !_isFullScreen
          ? AppBar(
              toolbarHeight: 0,
              backgroundColor: Colors.black,
            )
          : null,
      body: SafeArea(
        top: !_isFullScreen,
        bottom: false,
        left: !_isFullScreen,
        right: !_isFullScreen,
        child: _isFullScreen ? _buildFullScreenPlayer() : _buildNormalPlayer(),
      ),
    );
  }

  Widget _buildNormalPlayer() {
    return Column(
      children: [
        Container(
          color: Colors.black,
          child: AspectRatio(
            aspectRatio: 16 / 9,
            child: Center(
              child: Stack(
                alignment: Alignment.center,
                children: [
                  _buildPlayerWidget(),
                  _buildControl(),
                  Obx(() => Visibility(
                        visible: _isLoading.value,
                        child: _buildLoadingWidget(),
                      )),
                ],
              ),
            ),
          ),
        ),
        Expanded(
          child: SingleChildScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            child: Padding(
              padding: const EdgeInsets.all(12.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildFilmInfo(),
                  const SizedBox(height: 20),
                  _buildActionButtons(),
                  const SizedBox(height: 20),
                  _buildEpisodeSelector(),
                  const SizedBox(height: 20),
                  _buildRecommendations(),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 视频加载动画
  Widget _buildLoadingWidget() {
    return Container(
      color: Colors.black.withOpacity(0.5),
      child: Center(
        child: Gif(
          height: 97,
          width: 71,
          autostart: Autostart.loop,
          image: const AssetImage('assets/images/loading.gif'),
        ),
      ),
    );
  }

  Widget _buildFullScreenPlayer() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.black,
      child: Stack(
        alignment: Alignment.center,
        children: [
          _buildPlayerWidget(),
          _buildControl(),
          Obx(() => Visibility(
                visible: _isLoading.value,
                child: _buildLoadingWidget(),
              )),
        ],
      ),
    );
  }

  Widget _buildControl() {
    return Positioned.fill(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: Column(
          children: [
            _buildControlTop(),
            const Spacer(),
            _buildControlBottom(),
          ],
        ),
        onTap: () {
          setState(() {
            _showControls = !_showControls;
          });
          if (_showControls) {
            _startHideControlsTimer();
          }
        },
      ),
    );
  }

  // 播放器
  Widget _buildPlayerWidget() {
    return Center(
      child: TXPlayerVideo(
        onRenderViewCreatedListener: (viewId) {
          _controller.setPlayerView(viewId);
        },
      ),
    );
  }

  // 顶部控制
  Widget _buildControlTop() {
    return AnimatedOpacity(
      opacity: _showControls ? 1.0 : 0.0,
      duration: const Duration(milliseconds: 300),
      child: Container(
        height: 50,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Colors.black.withOpacity(0.3), Colors.transparent],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        padding: EdgeInsets.symmetric(horizontal: _isFullScreen ? 50 : 10),
        child: Row(
          children: [
            GestureDetector(
              child: const Icon(Icons.arrow_back_ios, color: Colors.white),
              onTap: () {
                if (_isFullScreen) {
                  _toggleFullScreen();
                } else {
                  Get.back();
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  // --- 重构后的底部控制栏 ---
  Widget _buildControlBottom() {
    return Obx(
      () => AnimatedOpacity(
        opacity: _showControls ? 1.0 : 0.0,
        duration: const Duration(milliseconds: 300),
        child: Container(
          height: 50,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.transparent, Colors.black.withOpacity(0.3)],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          padding: EdgeInsets.symmetric(horizontal: _isFullScreen ? 50 : 10),
          child: Row(
            children: [
              // 播放/暂停按钮
              GestureDetector(
                onTap: () {
                  if (_isPlayEnd.value) {
                    _controller.seek(0);
                    _controller.resume();
                  } else if (_isPlaying.value) {
                    _controller.pause();
                    _isPlaying.value = false;
                  } else {
                    _controller.resume();
                  }
                  _startHideControlsTimer();
                },
                child: Icon(
                  _isPlaying.value ? Icons.pause : Icons.play_arrow,
                  color: Colors.white,
                ),
              ),
              const SizedBox(width: 8),
              // 进度条
              Expanded(
                child: Slider(
                  activeColor: Colors.white,
                  inactiveColor: Colors.white30,
                  value: _currentPosition.value.inMilliseconds.toDouble(),
                  min: 0,
                  max: _totalDuration.value.inMilliseconds.toDouble().clamp(0.0, double.infinity),
                  onChanged: (value) {
                    // 拖动时更新显示的时间，提供更好的用户体验
                    _currentPosition.value = Duration(milliseconds: value.toInt());
                  },
                  onChangeStart: (value) {
                    // 开始拖动时，取消隐藏控件的计时器
                    _hideControlsTimer?.cancel();
                  },
                  onChangeEnd: (value) {
                    // 拖动结束后，跳转到指定位置并重新启动计时器
                    _controller.seek((value.toInt() ~/ 1000).toDouble()); // seek方法需要int类型的秒
                    _startHideControlsTimer();
                  },
                ),
              ),
              // 时间显示
              Text(
                '${_formatDuration(_currentPosition.value)} / ${_formatDuration(_totalDuration.value)}',
                style: const TextStyle(color: Colors.white, fontSize: 12),
              ),
              const SizedBox(width: 8),
              // 全屏按钮
              GestureDetector(
                onTap: _toggleFullScreen,
                child: Icon(
                  _isFullScreen ? Icons.fullscreen_exit : Icons.fullscreen,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = duration.inHours;
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    if (hours > 0) {
      return [twoDigits(hours), minutes, seconds].join(':');
    } else {
      return [minutes, seconds].join(':');
    }
  }

  void _startHideControlsTimer() {
    _hideControlsTimer?.cancel();
    _hideControlsTimer = Timer(const Duration(seconds: 3), () {
      if (mounted && _showControls) {
        setState(() => _showControls = false);
      }
    });
  }

  // --- 以下UI部分未作修改 ---

  Widget _buildFilmInfo() {
    return Obx(
      () => Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            height: 60,
            width: 50,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: film.value.vodPic != null
                  ? Image.network(
                      film.value.vodPic ?? '',
                      fit: BoxFit.cover,
                    )
                  : SizedBox(),
            ),
          ),
          SizedBox(width: 10),
          Expanded(
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 标题
                    Expanded(
                      child: Text(
                        film.value.vodName ?? '',
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                        maxLines: 2,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                // 标签和热度
                Row(
                  children: [
                    const Icon(Icons.favorite, color: Colors.red, size: 16),
                    const SizedBox(width: 4),
                    Text(
                      '${film.value.vodHits}',
                      style: const TextStyle(color: Colors.red),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        '${film.value.vodArea} / ${film.value.vodYear} / ${film.value.vodClass?.replaceAll(",", " / ")}',
                        style: const TextStyle(color: Colors.grey, fontSize: 12),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建操作按钮行
  Widget _buildActionButtons() {
    Widget buildButton(IconData icon, String label) {
      return Column(
        children: [
          Icon(
            icon,
            color: Colors.grey[700],
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              color: Colors.grey[700],
              fontSize: 12,
            ),
          ),
        ],
      );
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        GestureDetector(
          child: buildButton(Icons.notifications_active_outlined, '催更'),
          onTap: () {
            Fluttertoast.showToast(
              msg: "开发中",
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0,
            );
          },
        ),
        GestureDetector(
          child: buildButton(Icons.cloud_download_outlined, '下载'),
          onTap: () {
            Fluttertoast.showToast(
              msg: "开发中",
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0,
            );
          },
        ),
        GestureDetector(
          child: buildButton(Icons.favorite_border, '追剧'),
          onTap: () => addVideoRecord(film.value.vodId!.toString(), "1"),
        ),
        buildButton(Icons.share_outlined, '分享'),
      ],
    );
  }

  /// 构建分集选择区域
  Widget _buildEpisodeSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 【修改】这里的 onTap 事件
        GestureDetector(
          onTap: _showEpisodeBottomSheet, // 调用我们新加的方法
          child: const Row(
            children: [
              Text(
                '选集',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Spacer(),
              Text(
                '更多',
                style: TextStyle(color: Colors.grey),
              ),
              Icon(
                Icons.arrow_forward_ios,
                size: 14,
                color: Colors.grey,
              ),
            ],
          ),
        ),
        const SizedBox(height: 10),
        SizedBox(
          height: 40,
          child: Obx(
            () => ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: videoItemList.length,
              itemBuilder: (context, index) {
                final item = videoItemList[index];
                // 【修改】使用 selectedEpisodeName 进行判断
                final isSelected = selectedEpisodeCode.value == item.code;
                return GestureDetector(
                  onTap: () {
                    if (!isSelected) {
                      selectedEpisodeCode.value = item.code;
                      selectEpisode(item.code); // 传入整个 VideoItem 对象
                    }
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    margin: const EdgeInsets.only(right: 8),
                    decoration: BoxDecoration(
                      color: isSelected ? Colors.pink.withOpacity(0.1) : Colors.grey.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                      border: isSelected ? Border.all(color: Colors.pink, width: 1) : null,
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      item.name,
                      style: TextStyle(
                        color: isSelected ? Colors.pink : Colors.black87,
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ),
      ],
    );
  }

  /// 【新增】触发底部选集面板的方法
  void _showEpisodeBottomSheet() {
    // --- 开始计算剩余高度 ---
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;
    final screenHeight = mediaQuery.size.height;

    // 获取状态栏的高度
    final statusBarHeight = mediaQuery.viewPadding.top;

    // 计算播放器的高度（宽度 / 宽高比）
    const playerAspectRatio = 16 / 9;
    final playerHeight = screenWidth / playerAspectRatio;

    // 计算 Scaffold body 中，播放器下方的剩余可用高度
    // 注意：因为你的 AppBar.toolbarHeight 为 0，所以不需要减去 AppBar 的高度
    final remainingHeight = screenHeight - statusBarHeight - playerHeight;
    // isScrollControlled: true 允许多次弹出层内容根据自身高度调整
    // safeArea: true 避免内容被系统UI（如刘海、底部导航条）遮挡
    Get.bottomSheet(
      SafeArea(
        child: Container(
          // 限制最大高度，防止内容过多时占满全屏
          constraints: BoxConstraints(maxHeight: remainingHeight),
          child: Column(
            mainAxisSize: MainAxisSize.min, // 高度自适应内容
            children: [
              // 1. 标题和关闭按钮
              Padding(
                padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text('选集', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () => Get.back(),
                    ),
                  ],
                ),
              ),
              // 2. 剧集网格
              Expanded(
                child: Obx(() {
                  // 根据排序状态决定列表顺序
                  final List<VideoItem> displayList = isEpisodeListReversed.value ? videoItemList.reversed.toList() : videoItemList;

                  return GridView.builder(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2, // 两列
                      childAspectRatio: 3.5, // 宽高比
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                    ),
                    itemCount: displayList.length,
                    itemBuilder: (context, index) {
                      final item = displayList[index];
                      final isSelected = selectedEpisodeCode.value == item.code;
                      return GestureDetector(
                        onTap: () {
                          if (!isSelected) {
                            selectedEpisodeCode.value = item.code;
                            selectEpisode(item.code);
                          }
                          Get.back(); // 选择后关闭弹窗
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.grey.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          alignment: Alignment.center,
                          child: isSelected
                              ? const Icon(Icons.bar_chart, color: Colors.red)
                              : Text(
                                  item.name,
                                  style: const TextStyle(color: Colors.black87),
                                  textAlign: TextAlign.center,
                                ),
                        ),
                      );
                    },
                  );
                }),
              ),
              // 3. 排序按钮
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 12.0),
                child: Obx(
                  () => Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      GestureDetector(
                        onTap: () => isEpisodeListReversed.value = false,
                        child: Text(
                          '正序',
                          style: TextStyle(
                            color: !isEpisodeListReversed.value ? Colors.red : Colors.black,
                            decoration: !isEpisodeListReversed.value ? TextDecoration.underline : TextDecoration.none,
                            decorationColor: Colors.red,
                          ),
                        ),
                      ),
                      const SizedBox(width: 40),
                      GestureDetector(
                        onTap: () => isEpisodeListReversed.value = true,
                        child: Text(
                          '倒序',
                          style: TextStyle(
                            color: isEpisodeListReversed.value ? Colors.red : Colors.black,
                            decoration: isEpisodeListReversed.value ? TextDecoration.underline : TextDecoration.none,
                            decorationColor: Colors.red,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      barrierColor: Colors.transparent,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(0)),
      ),
    );
  }

  /// 构建相关推荐区域
  Widget _buildRecommendations() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '相关推荐',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 10),
        SizedBox(
          height: 180, // 根据内容调整高度
          child: Obx(
            () => ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: recommendFilmList.length,
              itemBuilder: (context, index) {
                final item = recommendFilmList[index];
                return _buildRecommendationCard(item);
              },
            ),
          ),
        ),
      ],
    );
  }

  /// 构建单个推荐卡片
  Widget _buildRecommendationCard(Film film) {
    return GestureDetector(
      onTap: () async {
        bool isLogin = await authController.check();
        if (isLogin) {
          String url = await authController.getVideo(film.vodId!.toString(), 0);
          Get.offAndToNamed(
            '/film',
            arguments: {'url': url, 'vodId': film.vodId!.toString()},
          );
        }
      },
      child: Container(
        width: 110,
        margin: const EdgeInsets.only(right: 10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: CachedNetworkImage(
                    imageUrl: film.vodPic!,
                    height: 140,
                    width: 110,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(color: Colors.grey[200]),
                    errorWidget: (context, url, error) => const Icon(Icons.error),
                  ),
                ),
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 4),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(8),
                        bottomRight: Radius.circular(8),
                      ),
                    ),
                    child: Text(
                      film.vodRemarks!,
                      style: const TextStyle(color: Colors.white, fontSize: 10),
                      textAlign: TextAlign.center,
                    ),
                  ),
                )
              ],
            ),
            const SizedBox(height: 4),
            Text(
              film.vodName!,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
            ),
          ],
        ),
      ),
    );
  }
}
